package com.jb.repair.acticity;

import android.content.Intent;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.drawable.ColorDrawable;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Bundle;
import android.provider.MediaStore;
import android.text.Editable;
import android.text.TextWatcher;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.PopupWindow;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;

import com.jb.repair.F1Application;
import com.jb.repair.R;
import com.jb.repair.common.AppConfig;
import com.jb.repair.common.Constants;
import com.jb.repair.dao.Db;
import com.jb.repair.dao.LocalDbDao;
import com.jb.repair.dao.ModifyDb;
import com.jb.repair.dao.QueryDb;
import com.jb.repair.model.FileLbModel;
import com.jb.repair.model.QxjlModel;
import com.jb.repair.model.ResultModel;
import com.jb.repair.net.HttpClient;
import com.jb.repair.util.BitmapUtil;
import com.jb.repair.util.MessageUtil;
import com.jb.repair.util.TimeUtil;
import com.jb.repair.view.TitleView;

import org.json.JSONException;
import org.json.JSONObject;

import java.io.File;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;

public class BugRegisterActivity extends BaseActivity {
    private TextView tv_dev_name, tv_item_name, tv_time;
    private EditText et;
    ResultModel model = new ResultModel();

    private TitleView titleView;
    private Spinner sp1, sp2;
    private ImageView imageView;
    private Db db;
    private PopupWindow window;
    private String uploadImagePath;
    private String uploadImageFileName;
    HashMap<String, String> map1;
    HashMap<String, String> map2;
    List<String> list1;
    List<String> list2;
    private EditText ed_disc;
    private String dev_id;

    private String intro;
    private String TAG = "BugRegisterActivity";
    private LocalDbDao dao;
    private String defect_id;
    private String result_id;
    private QxjlModel defect;
    private String imgPath;
    private Boolean is_change = false;
    private Boolean is_img_change = false;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_bug_register);
        defect_id = UUID.randomUUID().toString();
        result_id = getIntent().getStringExtra("resultId");
        defect = QueryDb.getInstance(getApplicationContext()).getDefectByResultId(result_id);
        dao = LocalDbDao.getInstance(getApplication());
        db = Db.getInstance(this);
        list1 = new ArrayList<String>();
        list2 = new ArrayList<String>();
        map1 = new HashMap<String, String>();
        map2 = new HashMap<String, String>();
        initview();
    }

    public void initview() {
        tv_dev_name = (TextView) findViewById(R.id.tv1);
        tv_item_name = (TextView) findViewById(R.id.tv2);
        tv_time = (TextView) findViewById(R.id.tv3);
        et = (EditText) findViewById(R.id.ll_tv6);
        tv_dev_name.setText(getIntent().getStringExtra("devName"));
        tv_item_name.setText(getIntent().getStringExtra("itemName"));
        tv_time.setText(TimeUtil.getSystemTime());
        dev_id = getIntent().getStringExtra("equip_id");
        titleView = (TitleView) findViewById(R.id.titleView);
        sp1 = (Spinner) findViewById(R.id.sp1);
        sp2 = (Spinner) findViewById(R.id.sp2);
        imageView = (ImageView) findViewById(R.id.iv_iv);

        imgPath = AppConfig.UPLOAD_PATH + defect.attachment + ".jpg";
        File f = new File(imgPath);
        if(!f.exists()){
            imgPath = AppConfig.ATTACHMENT_PATh + defect.attachment + ".jpg";
        }
        Bitmap bitmap = BitmapFactory.decodeFile(imgPath);
        imageView.setImageBitmap(bitmap);

        et.setText(defect.defect_describe);
        et.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
                is_change = true;
            }

            @Override
            public void afterTextChanged(Editable s) {

            }
        });

        Cursor cursor = db.getCursor("Select * from TB_SYS_CODE where LABEL_CODE='03025'");
        while (cursor.moveToNext()) {
            String key = cursor.getString(cursor.getColumnIndex("CODE_NAME"));
            String value = cursor.getString(cursor.getColumnIndex("CODE"));
            list1.add(key);
            map1.put(key, value);
        }
//        Log.e("Tag", list1.toString());
//        Log.e("Tag", String.valueOf(map1.entrySet()));
        ArrayAdapter arrayAdapter1 = new ArrayAdapter(this, R.layout.list_item, list1);
        arrayAdapter1.setDropDownViewResource(android.R.layout.select_dialog_item);
        sp1.setAdapter(arrayAdapter1);
        //缺陷类型

        String sblx = db.getName("eq_type_id", "TB_EQ_BASICINFO", "guid", dev_id);
        String type_code = db.getName("eq_type_code", "TB_EQ_TYPE", "guid", sblx);
        Cursor cursor1 = db.getCursor("select * from TB_EQ_DEFECT_TYPE where eq_type_code ='" + type_code + "'");
        while (cursor1.moveToNext()) {
            String type = cursor1.getString(cursor1.getColumnIndex("defect_type"));
            String type_id = cursor1.getString(cursor1.getColumnIndex("guid"));
            list2.add(type);
            map2.put(type, type_id);
        }
        //Log.e("Tag", String.valueOf(map2.entrySet()));
        ArrayAdapter arrayAdapter2 = new ArrayAdapter(this, R.layout.list_item, list2);
        arrayAdapter2.setDropDownViewResource(android.R.layout.select_dialog_item);
        sp2.setAdapter(arrayAdapter2);

        sp1.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
            @Override
            public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
                model.defect_level_id = map1.get(list1.get(position));
            }

            @Override
            public void onNothingSelected(AdapterView<?> parent) {
            }
        });

        sp2.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
            @Override
            public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
                model.defect_type_id = map2.get(list2.get(position));
            }

            @Override
            public void onNothingSelected(AdapterView<?> parent) {
            }
        });


        titleView.setOnClickListener(new TitleView.OnTitleViewClickListener() {
            @Override
            public void onLeftImageClick(View view) {
                super.onLeftImageClick(view);
                finish();
            }

            @Override
            public void onRightTextClick(View view) {
                super.onRightTextClick(view);
                model.GUID = result_id;
                model.plan_task_detail_id = getIntent().getStringExtra("planId");
                model.is_abnormal = "F";
                model.is_defect = "T";
                model.defect_desc = et.getText().toString();
                model.equip_id = dev_id;
                model.attachment = uploadImageFileName;
                model.defect_id = defect_id;
                model.is_must_today = getIntent().getStringExtra("isMust");
                Log.i(TAG,"model.is_must_today == "+model.is_must_today);
                if (is_change) {
                    ModifyDb.getInstance(getApplicationContext()).delectByResultId(result_id);
                    Log.i("main", "A");
                    if(!is_img_change){
                        Log.i("main","B");
                        FileLbModel fileLbmodel = new FileLbModel();
                        fileLbmodel.guid = defect.attachment;
                        fileLbmodel.wjmc = defect.attachment + ".jpg";
                        fileLbmodel.lx = "jpg";
                        fileLbmodel.clounm = "attachment";
                        fileLbmodel.table = "TB_EQ_ABNORMAL";
                        fileLbmodel.lineId = defect_id;
                        fileLbmodel.TIMEPOINT = TimeUtil.getSystemTime();
                        ModifyDb.getInstance(getApplicationContext()).insertFile(fileLbmodel);
                        model.attachment = defect.attachment;
                    }
                    ModifyDb.getInstance(BugRegisterActivity.this).regist(model);
                    Toast.makeText(getApplicationContext(), "保存成功", Toast.LENGTH_SHORT).show();
                }else {
                    MessageUtil.showToast(getApplicationContext(), "未做修改");
                }

                finish();
            }
        });
        imageView.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                View popView = LayoutInflater.from(BugRegisterActivity.this).inflate(R.layout.layout, null);
                window = new PopupWindow(popView, 200, LinearLayout.LayoutParams.WRAP_CONTENT, true);
                window.setFocusable(true);
                ColorDrawable dw = new ColorDrawable(0x00000000);
                window.setBackgroundDrawable(dw);
                window.showAsDropDown(v);
                uploadImageFileName = UUID.randomUUID().toString();
                popView.findViewById(R.id.tv_local).setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        window.dismiss();
                        Intent intentGallery = new Intent(Intent.ACTION_PICK, MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
                        startActivityForResult(intentGallery, 1);//这里不一定是1，可以是任意int型的数据
                    }
                });
                popView.findViewById(R.id.tv_camera).setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        window.dismiss();

                        /* 选择拍照 核心代码*/
                        Intent intentCamera = new Intent();
                        intentCamera.setAction(MediaStore.ACTION_IMAGE_CAPTURE);
                        intentCamera.addCategory(Intent.CATEGORY_DEFAULT);
                        File file = new File(AppConfig.UPLOAD_PATH); //path代表拍照结束后照片要保存到的目录，如/sdcard/upload/image/
                        if (!file.exists()) {
                            file.mkdirs();
                        }
                        uploadImagePath = AppConfig.UPLOAD_PATH + uploadImageFileName + ".jpg";
                        file = new File(uploadImagePath);
                        intentCamera.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(file));
                        startActivityForResult(intentCamera, 0);//这里不一定是0，可以是任意int型的数据

                    }
                });

            }
        });
    }

    /* 拍照返回后在 onActivityResult()方法中进行处理 */
    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        is_img_change = true;
        is_change = true;
        switch (requestCode) {
            case 0:
                /* 在这里对拍照的图片进行处理，如上传*/
                String path = AppConfig.UPLOAD_PATH + uploadImageFileName + ".jpg";
                Bitmap bm1 = BitmapFactory.decodeFile(path);
                if (bm1 != null) {
                    imageView.setImageBitmap(bm1);//imageView代表要显示图片的view
                    //imageView.setBackground(null);
                    FileLbModel model = new FileLbModel();
                    model.guid = uploadImageFileName;
                    model.wjmc = uploadImageFileName + ".jpg";
                    model.lx = "jpg";
                    model.clounm = "attachment";
                    model.table = "TB_EQ_DEFECT";
                    model.lineId = defect_id;
                    model.TIMEPOINT = TimeUtil.getSystemTime();
                    ModifyDb.getInstance(getApplicationContext()).insertFile(model);
                }


                break;

            case 1:
                /* 在这里对选取的图片进行处理，如上传*/
                if (data != null) {
                    Uri uri = data.getData();//这个uri指向刚才选中的图片
                    if (uri != null) {
                        //获取该图片的具体路径
                        Cursor cursor = BugRegisterActivity.this.getContentResolver().query(uri, null, null, null, null);
                        if (cursor.moveToFirst()) {
                            String url = cursor.getString(1);//url会指向该图片
                            Log.i(TAG, url);

                            //未对照片进行处理

                            /* 接下来就可以对该图片进行处理了，如显示到指定位置 */
                            // BitmapFactory.Options option = new BitmapFactory.Options();
                            //此处需要一个ImageTools
                            // option.inSampleSize = ImageTools.getImageScale(url);

                            // Bitmap bm = BitmapFactory.decodeFile(url, option);
                            Bitmap bm = BitmapFactory.decodeFile(url);

                            if (bm != null) {
                                String path1 = AppConfig.UPLOAD_PATH + uploadImageFileName + ".jpg";
                                imageView.setImageBitmap(bm);//imageView代表要显示图片的view
                                //imageView.setBackground(null);
                                if (BitmapUtil.saveBitmapFile(bm, path1)) {
                                    Log.i("main","图片保存成功");
                                    FileLbModel model = new FileLbModel();
                                    model.guid = uploadImageFileName;
                                    model.wjmc = uploadImageFileName + ".jpg";
                                    model.lx = "jpg";
                                    model.TIMEPOINT = TimeUtil.getSystemTime();
                                    model.clounm = "attachment";
                                    model.table = "TB_EQ_DEFECT";
                                    model.lineId = defect_id;
                                    ModifyDb.getInstance(getApplicationContext()).insertFile(model);
                                }
                            }
                        }

                    }
                    break;
                }
        }

    }



}
